package com.jiuyin.dianjing.ui.fragment.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.helper.ApiHelper;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper;
import com.jiuyin.dianjing.ui.activity.main.MainActivity;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.RegexTool;
import com.jiuyin.dianjing.util.ToastUtil;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CHECK_CODE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CODE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MOBILE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NATION_CODE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PASSWORD;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_NATION_CODE;
import static com.jiuyin.dianjing.constant.AppConstant.COUNT_DOWN_TIME_NAME;
import static com.jiuyin.dianjing.constant.AppConstant.COUNT_DOWN_TIME_UNIT;
import static com.jiuyin.dianjing.constant.AppConstant.COUNT_DOWN_VERIFY_CODE_TIME;
import static com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper.ACTION_SET;
import static com.jiuyin.dianjing.jiguang.TagAliasOperatorHelper.sequence;
import static com.jiuyin.dianjing.util.DesUtil.getMd5;

/**
 * 登录页中的密码登录
 */
public class LoginFragment extends Fragment {
    public static final String KEY_BUSINESS_TYPE = "business_type";
    public static final int TYPE_FORGOT_PWD = 2;
    public static final int TYPE_REGISTER = 3;
    public static final int TYPE_LOGIN_WITH_PWD = 0;
    public static final int TYPE_LOGIN_WITH_IDENTIFY_CODE = 1;
    private static String MOBILE = "";
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.edt_verify_code)
    EditText etCode;
    @BindView(R.id.bt_get_code)
    Button btGetCode;
    @BindView(R.id.divider2)
    View divider2;
    @BindView(R.id.layout_root)
    ViewGroup rootView;
    private int mType;
    private Unbinder mUnBinder;
    private String mCheckCode;//验证识别码
    private CountDownTimer mTimer;

    public static LoginFragment newInstance(int type) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putInt(KEY_BUSINESS_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mType = getArguments().getInt(KEY_BUSINESS_TYPE, TYPE_LOGIN_WITH_PWD);
        View root = inflater.inflate(R.layout.fragment_login, container, false);
        mUnBinder = ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
        String mobile = HelperApplication.getMobile();
        if (!TextUtils.isEmpty(mobile)) {
            etMobile.setText(mobile);
        }
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                MOBILE = etMobile.getText().toString();
            }
        });

        switch (mType) {
            case TYPE_FORGOT_PWD:
                etPwd.setHint("请输入新密码：6-20个字符");
                break;
            case TYPE_REGISTER:
                etPwd.setHint("请输入密码：6-20个字符");
                break;
            case TYPE_LOGIN_WITH_PWD:
                etCode.setVisibility(View.GONE);
                btGetCode.setVisibility(View.GONE);
                divider2.setVisibility(View.GONE);
                break;
            case TYPE_LOGIN_WITH_IDENTIFY_CODE:
                etPwd.setVisibility(View.GONE);
                divider2.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (null != etMobile) {
                etMobile.setText(MOBILE);
                etMobile.setSelection(etMobile.getText().length());
            }
        }
    }

    @Override
    public void onDestroyView() {
        mUnBinder.unbind();
        super.onDestroyView();
    }

    @OnClick({R.id.bt_get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_get_code:
                sendVerifyCode();
                break;
        }
    }


    /**
     * 发送验证码
     */
    private void sendVerifyCode() {
        String mPhoneNumber = etMobile.getText().toString();
        if (!TextUtils.isEmpty(mPhoneNumber)) {
            HashMap<String, Object> params = new HashMap<>();
            params.put(KEY_NATION_CODE, VALUE_NATION_CODE);
            params.put(KEY_MOBILE, mPhoneNumber);
            JSONObject jsonObject = new JSONObject(params);
            String content = jsonObject.toString();
            ApiHelper.getInstance(getContext()).appSendSmsApi(content, data -> {
                setStatus();
                mCheckCode = data;
            });
        } else {
            ToastUtil.showShort(R.string.login_phone_hint);
        }
    }

    private void setStatus() {
        if (null != mTimer) {
            mTimer.cancel();
        }
        btGetCode.setEnabled(false);
        mTimer = new CountDownTimer(COUNT_DOWN_VERIFY_CODE_TIME, COUNT_DOWN_TIME_UNIT) {
            @Override
            public void onTick(long millisUntilFinished) {
                btGetCode.setText((millisUntilFinished / COUNT_DOWN_TIME_UNIT + 1) + COUNT_DOWN_TIME_NAME);
            }

            @Override
            public void onFinish() {
                btGetCode.setEnabled(true);
                btGetCode.setText(R.string.login_get_verify_code);
            }
        };
        mTimer.start();
    }


    //region 输入验证
    private boolean validateInput() {
        if (!validateMobile()) {
            return false;
        }
        switch (mType) {
            case TYPE_FORGOT_PWD:
            case TYPE_REGISTER:
                if (!validatePwd()) {
                    return false;
                }
                if (!validateIdentifyCode()) {
                    return false;
                }
                break;
            case TYPE_LOGIN_WITH_IDENTIFY_CODE:
                return validateIdentifyCode();
        }
        return true;
    }

    private boolean validateMobile() {
        boolean result = true;
        if (etMobile != null) {
            String phone = etMobile.getText().toString();
            if (!TextUtils.isEmpty(phone)) {
                if (!RegexTool.instance().isMobile(phone)) {
                    ToastUtil.showShort(R.string.login_normal_phone_tips);
                    result = false;
                }
            } else {
                ToastUtil.showShort(R.string.login_tips);
                result = false;
            }
        }
        return result;
    }

    private boolean validatePwd() {
        String pwd = etPwd.getText().toString();
        if (!TextUtils.isEmpty(pwd)) {
            if (!RegexTool.instance().isPassword(pwd)) {
                ToastUtil.showShort(R.string.login_pwd_hint);
                return false;
            }
        } else {
            ToastUtil.showShort(R.string.login_tips);
            return false;
        }
        return true;
    }

    private boolean validateIdentifyCode() {
        String code = etCode.getText().toString();
        if (TextUtils.isEmpty(code)) {
            ToastUtil.showShort(R.string.login_verify_code_null_tips);
            return false;
        }
        return true;
    }
    //endregion

    public void submit() {
        if (!validateInput()) {
            return;
        }
        IMEUtil.hideInputMethod(getActivity());
        switch (mType) {
            case TYPE_LOGIN_WITH_PWD:
                loginWithPwd();
                break;
            case TYPE_FORGOT_PWD:
            case TYPE_REGISTER:
            case TYPE_LOGIN_WITH_IDENTIFY_CODE:
                checkSms();
                break;
        }
    }


    //region 网络请求

    /**
     * 短信验证
     */
    private void checkSms() {
        String mPhoneNumber = etMobile.getText().toString();
        String verifyCode = etCode.getText().toString().trim();
        if (!TextUtils.isEmpty(mPhoneNumber) && !TextUtils.isEmpty(mCheckCode)) {
            HashMap<String, Object> params = new HashMap<>();
            params.put(KEY_CODE, verifyCode);
            params.put(KEY_CHECK_CODE, mCheckCode);
            JSONObject jsonObject = new JSONObject(params);
            ApiHelper.getInstance(getContext()).appMsgCheckApi(jsonObject.toString(), data -> {
                if (data) {
                    switch (mType) {
                        case TYPE_FORGOT_PWD:
                            setNewPwd();
                            break;
                        case TYPE_REGISTER:
                            register();
                            break;
                        case TYPE_LOGIN_WITH_IDENTIFY_CODE:
                            loginWithCode();
                            break;
                    }
                }
            });
        } else {
            ToastUtil.showShort(R.string.login_msg_verify_code_hint);
        }
    }

    private void register() {
        String mPhoneNumber = etMobile.getText().toString();
        HashMap<String, String> paramsMobile = new HashMap<>();
        paramsMobile.put(KEY_MOBILE, mPhoneNumber);
        String md5Pwd = getMd5(etPwd.getText().toString());
        paramsMobile.put(KEY_PASSWORD, md5Pwd);
        JSONObject jsonMobile = new JSONObject(paramsMobile);
        ApiHelper.getInstance(getContext()).appRegisterApi(jsonMobile.toString(), ret -> {
            if (ret) {
                HelperApplication.setMobile(mPhoneNumber);
                jPushSetAlias();
                if (getActivity() != null) {
                    startActivity(new Intent(getActivity(), MainActivity.class));
                    getActivity().finish();
                }
            }
        });
    }

    private void loginWithPwd() {
        String phone = etMobile.getText().toString();
        String pwd = etPwd.getText().toString();
        String md5Pwd = getMd5(pwd);
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_MOBILE, phone);
        params.put(KEY_PASSWORD, md5Pwd);
        JSONObject jsonObject = new JSONObject(params);
        String content = jsonObject.toString();
        ApiHelper.getInstance(getContext()).appLoginWithPwdApi(content, data -> {
            if (data) {
                HelperApplication.setMobile(phone);
                jPushSetAlias();
                startActivity(new Intent(getActivity(), MainActivity.class));
                getActivity().finish();
            }
        });
    }

    private void jPushSetAlias() {
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = ACTION_SET;
        sequence++;
        tagAliasBean.alias = HelperApplication.getUserId();
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getActivity(), sequence, tagAliasBean);
    }

    private void loginWithCode() {
        String phone = etMobile.getText().toString();
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_MOBILE, phone);
        JSONObject jsonObject = new JSONObject(params);
        String content = jsonObject.toString();
        ApiHelper.getInstance(getContext()).appLoginWithCodeApi(content, data -> {
            if (data) {
                HelperApplication.setMobile(phone);
                jPushSetAlias();
                startActivity(new Intent(getActivity(), MainActivity.class));
                getActivity().finish();
            }
        });
    }

    private void setNewPwd() {
        String newPwd = etPwd.getText().toString();
        String mPhoneNumber = etMobile.getText().toString();
        String pwdMd5 = getMd5(newPwd);
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_MOBILE, mPhoneNumber);
        params.put(KEY_PASSWORD, pwdMd5);
        params.put(KEY_CHECK_CODE, mCheckCode);
        JSONObject jsonObject = new JSONObject(params);
        ApiHelper.getInstance(getActivity()).appSetUserPwdApi(jsonObject.toString(), data -> {
            if (data) {
                jPushSetAlias();
                startActivity(new Intent(getActivity(), MainActivity.class));
                getActivity().finish();
            }
        });
    }

    public int getType() {
        return mType;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mTimer) {
            mTimer.cancel();
        }
    }

    interface SubmitCallback {
        void onSuccess();

        void onFail();
    }
}
